" opens all files/current file in the current buffer and closes the grep result buffer
function! OpenAllFilesInVimFunction()
  g/^\S\+\zs:\d\+:/normal nD
  g/^\S\+\zs-\d\+-/normal nD
  sort u
  %s/\(.*\)/e \1
  %d b
  bd!
  @b
  silent! unmap <cr>
  next
endfunction

function! OpenCurrentFileInVimFunction(...)
  s/^\ze\([^ :]\+\):\(\d\+\):/\1 \2 /
  normal 0"udaW"ldaW3u
  if a:0 > 0 && a:1 == 1
    if winnr('$') == 1
      execute 'vsp' @u
    else
      execute 'wincmd w|edit' @u
    endif
  else
    execute 'edit' @u
  endif
  @l
endfunction

function! OpenCurrentFileInVimDashFunction(...)
  s/^\ze\([^ :]\+\)-\(\d\+\)-/\1 \2 /
  normal 0"udaW"ldaW3u
  if a:0 > 0 && a:1 == 1
    if winnr('$') == 1
      execute 'vsp' @u
    else
      execute 'wincmd w|edit' @u
    endif
  else
    execute 'edit' @u
  endif
  @l
endfunction

" replace inline. This is useful when I edit something in the vim buffer after
" the tbgs search (pipe-to vim or pipe-to nvim), and I just want to update the
" corresponding file with my edits
function ReplaceAllInPlaceFunction()
  " escape special characters
  " TODO: this is ugly, find a solution that only needs one pass
  for i in range(0, 99)
    silent!%s/^[^:]\+:\d\+:.*[^\\]\zs\//\\\//
    silent!%s/^[^:]\+:\d\+:.*[^\\]\zs\~/\\\~/
    silent!%s/^[^:]\+:\d\+:.*[^\\]\zs\'/\\'/
  endfor
  " construct sed command: sed -i '' 'sec_command' file_name
  %s/\(^[^:]\+\):\(\d\+\):\(.*\)$/sed -i '' '\2s\/.*\/\3\/g' \1/g
  %!fish
  qa!
endfunction

function ReplaceCurrentLineInPlaceFunction()
  " escape special characters
  " TODO: this is ugly, find a solution that only needs one pass
  for i in range(0, 99)
    silent!s/^[^:]\+:\d\+:.*[^\\]\zs\//\\\//
    silent!s/^[^:]\+:\d\+:.*[^\\]\zs\~/\\\~/
    silent!s/^[^:]\+:\d\+:.*[^\\]\zs\'/\\'/
  endfor
  " construct sed command: sed -i '' 'sec_command' file_name
  s/\(^[^:]\+\):\(\d\+\):\(.*\)$/sed -i '' '\2s\/.*\/\3\/g' \1/g
  .!fish
endfunction

" mappings
nnoremap <space>o :silent! call OpenCurrentFileInVimFunction()<cr>
nnoremap <space><space>o :silent! call OpenCurrentFileInVimFunction(1)<cr>
nnoremap <space>- :silent! call OpenCurrentFileInVimDashFunction()<cr>
nnoremap <space><space>- :silent! call OpenCurrentFileInVimDashFunction(1)<cr>
nnoremap <space>O :silent! call OpenAllFilesInVimFunction()<cr>
nnoremap <space>gw :silent! call ReplaceCurrentLineInPlaceFunction()<cr>
nnoremap <space>gW :silent! call ReplaceAllInPlaceFunction()<cr>

" clean up mappings on buffer leave
autocmd BufLeave grep_result_*.tbgs nunmap <space>o
autocmd BufLeave grep_result_*.tbgs nunmap <space><space>o
autocmd BufLeave grep_result_*.tbgs nunmap <space>-
autocmd BufLeave grep_result_*.tbgs nunmap <space><space>-
autocmd BufLeave grep_result_*.tbgs nunmap <space>O
autocmd BufLeave grep_result_*.tbgs nunmap <space>gw
autocmd BufLeave grep_result_*.tbgs nunmap <space>gW
